/*********************************************************************************
Description: 
Author: SA12226114(Xin Zhu), SA12226139(Dan Shu)
Date: 2012-11 

Copyright (c) 2012-2022 School of Software Engineering of USTC, All rights reserved.

**********************************************************************************/


#include "server.h"


/*****************************************************************
Function Name: main
Description:
Parameter:  

@argc: argument count
@argv: argument vector

Author: 
Date:  
******************************************************************/
int main(int argc, char** argv)
{
    int listenfd, connfd;
    struct sockaddr_in servaddr;
    char buff[MAXLINE];
    int bytes_rev;

    /* generate a new socket for server end */
    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
        
        return 0;
    }
    
    /* initialize structure sockaddr_in with protocol family, ip, port number */
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(10000);
            
    /* bind socket and socket id */
    if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
    {
        printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
        
        return 0;
    }

    /* the second parameter is max number of client connection */
    if(listen(listenfd, 100) == -1)
    {
        printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
        
        return 0;
    }

    printf("======waiting for client's messages======\n");
    while(1)
    {
        /* accept messages from client */
        if((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1)
        {
            printf("accept socket error: %s(errno: %d)", strerror(errno), errno);
            
            continue;
        }

        /* put messages into buffer */
        bytes_rev = recv(connfd, buff, MAXLINE, 0);
        buff[bytes_rev] = '\0';
        
        printf("received message is : %s\n", buff);
        
        close(connfd);
    }

    close(listenfd);
}
